const app = getApp()
const db = wx.cloud.database()
const _ = db.command
const $ = _.aggregate
const to = app.require("lib/awaitTo")
const dayjs = app.require("lib/day")
const loginCheck = app.require("utils/loginCheck")

module.exports = {
    data: {
        comment: {
            list: [],
            page: 0,
            content: "",
            nowCommentIndex: "",
            inputHeight: 0,
            inputFocus: false,
            placeholder: "说说你的想法吧~",
            favorLoading: false,
        }
    },

    async getComment() {
        const [err, res] = await to(db.collection("comment")
            .aggregate()
            .match({
                _postId: this.data.postId
            })
            .project({
                replyNum: $.size('$reply'),
                reply: $.slice(["$reply", 3]),
                favorNum: $.size('$favor'),
                isFavor: $.in([this.data.user._id || '', '$favor']),
                content: true,
                createTime: true,
                user: true,
            })
            .sort({
                "createTime": -1
            })
            .end(), "getComment")
        if (err) { return }
        res.list = res.list.map(item => {
            item.createTime = dayjs().from(item.createTime)
            return item
        })
        const totalRes = await db.collection("comment")
            .where({ "_postId": this.data.postId })
            .count()

        this.setData({
            "comment.list": this.data.comment.list.concat(res.list),
            "comment.total": totalRes.total
        })
    },
    async sendComment() {
        if (this.data.comment.placeholder === "说说你的想法吧~") {
            // 评论文章
            this.addComment()
        } else {
            // 回复评论
            this.addReply()
        }
    },
    async addComment() {
        // 添加评论
        const createTime = new Date().getTime()
        const newComment = {
            user: {
                avatarUrl: this.data.user.avatarUrl,
                nickName: this.data.user.nickName
            },
            _postId: this.data.postId,
            content: this.data.comment.content,
            favor: [],
            reply: [],
            createTime
        }
        const [err, res] = await to(db.collection("comment").add({
            data: {
                ...newComment
            }
        }), "addComment")
        if (err) { return }
        this.addMessage({ type: "comment", content: this.data.comment.content })
        this.setData({
            "comment.list": [{
                ...newComment,
                userId: this.data.user._id,
                _id: res._id,
                isFavor: false,
                favorNum: 0,
                replyNum: 0,
                createTime: dayjs().from(createTime)
            }]
                .concat(this.data.comment.list)
        })

        wx.showToast({
            title: '评论成功',
            icon: "none"
        })
    },
    async addReply() {
        const createTime = new Date().getTime()
        const nowCommentIndex = this.data.comment.nowCommentIndex
        const newReply = {
            userId: this.data.user._id,
            nickName: this.data.user.nickName,
            content: this.data.comment.content,
            createTime
        }
        const [err, res] = await to(db.collection("comment").doc(this.data.comment.list[nowCommentIndex]._id)
            .update({
                data: {
                    reply: _.push(newReply)
                }
            }), "addReply")
        if (err) return
        this.setData({
            [`comment.list[${nowCommentIndex}].reply`]: [{
                ...newReply,
                createTime: dayjs(createTime).from()
            }]
                .concat(this.data.comment.list[nowCommentIndex].reply)
        })
        wx.showToast({
            title: '回复成功',
            icon: "none"
        })
    },
    async showComment() {
        if (await loginCheck()) { return }
        // 弹出评论框
        this.setData({
            "comment.inputFocus": true
        })
    },
    commentInput(e) {
        this.setData({
            "comment.content": e.detail.value
        })
    },
    inputFocus(e) {
        // 评论框聚焦
        this.setData({
            "comment.inputHeight": e.detail.height
        })
    },
    inputBlur() {
        // 评论框失焦
        this.setData({
            "comment.inputHeight": 0,
            "comment.inputFocus": false,
            "comment.placeholder": "说说你的想法吧~"
        })
    },
    async favorComment(e) {
        if (await loginCheck()) { return }
        const index = e.currentTarget.dataset.index
        if (this.data.comment.favorLoading) return
        const {
            _id,
            isFavor,
            favorNum
        } = this.data.comment.list[index]
        this.setData({
            "comment.favorLoading": true
        })
        const [err, res] = await to(db.collection("comment")
            .doc(_id)
            .update({
                data: {
                    favor: isFavor ? _.pull(this.data.user._id) : _.push(this.data.user._id)
                }
            }), "favorComment")
        this.setData({
            "comment.favorLoading": false
        })
        if (err) return
        const commentIsFavor = `comment.list[${index}].isFavor`
        const commentFavorNum = `comment.list[${index}].favorNum`
        this.setData({
            [commentIsFavor]: !isFavor,
            [commentFavorNum]: isFavor ? favorNum - 1 : favorNum + 1
        })
        wx.showToast({
            title: isFavor ? '取消点赞' : '点赞评论成功',
            icon: "none"
        })
    },
    replyComment(e) {

        this.showComment()
        const index = e.currentTarget.dataset.index
        const {
            user
        } = this.data.comment.list[index]
        this.setData({
            "comment.placeholder": `回复 ${user.nickName} 的评论`,
            "comment.nowCommentIndex": index
        })
    },
    showActionsheet(e) {

    }
}